package com.songyl.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.songyl.config.IsbnConfig;
import com.songyl.entity.Book;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author syl
 */
@Component
public class IsbnTool {
    @Autowired
    IsbnConfig  isbnConfig;

    /**
     * @param ISBN
     * @return
     */
    public Book getBookByISBN(String ISBN){
        Book  book=new Book();

        String source = "market";

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String datetime = sdf.format(cd.getTime());
        // 签名
        String auth = null;
        try {
            auth = calcAuthorization(source, isbnConfig.secretId, isbnConfig.secretKey, datetime);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        // 请求方法
        String method = "GET";
        // 请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("X-Source", source);
        headers.put("X-Date", datetime);
        headers.put("Authorization", auth);

        // 查询参数
        Map<String, String> queryParams = new HashMap<String, String>();
        queryParams.put("isbn",ISBN);
        // body参数
        Map<String, String> bodyParams = new HashMap<String, String>();

        // url参数拼接
        String url = isbnConfig.url;
        if (!queryParams.isEmpty()) {
            try {
                url += "?" + urlencode(queryParams);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setRequestMethod(method);

            // request headers
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }

            // request body
            Map<String, Boolean> methods = new HashMap<>();
            methods.put("POST", true);
            methods.put("PUT", true);
            methods.put("PATCH", true);
            Boolean hasBody = methods.get(method);
            if (hasBody != null) {
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                conn.setDoOutput(true);
                DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                out.writeBytes(urlencode(bodyParams));
                out.flush();
                out.close();
            }

            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            String result = "";
            while ((line = in.readLine()) != null) {
                result += line;
            }

//            String result = "";
//            result="                {                  \"showapi_res_error\": \"\",                  " +
//                    "\"showapi_res_id\": \"624c55db0de3761c73803075\",                  " +
//                    "\"showapi_res_code\": 0,                  " +
//                    "\"showapi_fee_num\": 1,                  " +
//                    "\"showapi_res_body\": {" +
//                    "\"ret_code\":0," +
//                    "\"remark\":\"success\"," +
//                    "\"data\":{\"author\":\"（英）杰瑞米・斯坦格鲁（美）詹姆斯・加维\",\"binding\":\"平装-胶订\",\"edition\":\"\",\"format\":\"32开\",\"gist\":\"★英国皇家哲学学会、《哲学家杂志》推荐全民阅读选书。 ★《哲学家杂志》创办人杰瑞米 斯坦格鲁博士，英国皇家哲学学会秘书詹姆斯 加维博士，联合为大众读者创作的哲学入门经典，连续畅销欧美12年。 ★每10分钟读懂一位哲学家，快速了解西方哲学2000多年发展历程。 ★从苏格拉底到福柯，走进伟大哲学家们的精神世界。与哲学家们一起，优化思维逻辑，全面提升思考力。 ★每一个时期、流派、代表人物及其观点、成就 但凡你想知道的，都可以在此书中找到。 ★把错综复杂的哲学发展脉络梳理成一本极简的哲学史书，这是重大的成就，同时也极有难度，但是这部著作成功了。 《卫报》 ★作者精彩绝伦的文笔和恰到好处的举例，令积淀2000多年的哲学史读起来轻松、有趣多了。 《每日电讯报》\",\"img\":\"http://static1.showapi.com/app2/isbn/559/ab6b2ae28db64664963d9b493de211f5.jpg\",\"isbn\":\"9787559624857\",\"page\":\"285\",\"paper\":\"胶版纸\",\"price\":\"42.00\",\"produce\":\"\",\"pubdate\":\"2018-11\",\"publisher\":\"北京联合出版有限公司\",\"title\":\"极简西方哲学史\"}}                }                \n";

            JSONObject o=JSON.parseObject(result);

            //接口失败
            if(o.getInteger("showapi_res_code")!=0){
                book.setIsbn(ISBN);
                return book;

            }
            JSONObject body=o.getJSONObject("showapi_res_body");

            //没有查到
            if(body.getInteger("ret_code")==-1){
                book.setIsbn(ISBN);
                return book;

            }
            JSONObject data=body.getJSONObject("data");



            book=data.toJavaObject(Book.class);
            System.out.println(book.toString());

        } catch (Exception e) {
            book.setIsbn(ISBN);
            System.out.println(e);
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return book;

    }
    public static String calcAuthorization(String source, String secretId, String secretKey, String datetime)
            throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        String signStr = "x-date: " + datetime + "\n" + "x-source: " + source;
        Mac mac = Mac.getInstance("HmacSHA1");
        Key sKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), mac.getAlgorithm());
        mac.init(sKey);
        byte[] hash = mac.doFinal(signStr.getBytes("UTF-8"));
        String sig = new BASE64Encoder().encode(hash);

        String auth = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"" + sig + "\"";
        return auth;
    }

    public static String urlencode(Map<?, ?> map) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (sb.length() > 0) {
                sb.append("&");
            }
            sb.append(String.format("%s=%s",
                    URLEncoder.encode(entry.getKey().toString(), "UTF-8"),
                    URLEncoder.encode(entry.getValue().toString(), "UTF-8")
            ));
        }
        return sb.toString();
    }
}
